﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

using LINQToolKit.Web;
using LINQToolKit.GData;

namespace LINQToolKit.Douban
{
    public sealed class DoubanRequest : HttpRequestBase
    {
        public string ApiKey { get; set; }
        public string ApiKeySecret { get; set; }
        public string AccessToken { get; set; }
        public string AccessTokenSecret { get; set; }

        public DoubanRequest()
        {
            this.ContentType = "application/atom+xml";
        }

        private bool RequireSecureAccess
        {
            get
            {
                bool result = string.IsNullOrEmpty(ApiKey) ||
                    string.IsNullOrEmpty(ApiKeySecret) ||
                    string.IsNullOrEmpty(AccessToken) ||
                    string.IsNullOrEmpty(AccessTokenSecret);

                return !result;
            }
        }

        public override RequestResult ExecuteInsert(Uri requestUrl, string post)
        {
            return base.Execute(requestUrl, "POST", post);
        }

        public override RequestResult ExecuteUpdate(Uri requestUrl, string post)
        {
            return base.Execute(requestUrl, "PUT", post);
        }

        public override RequestResult ExecuteSelect(Uri requestUrl, string post)
        {
            return base.Execute(requestUrl, "GET", post);
        }

        public override RequestResult ExecuteDelete(Uri requestUrl, string post)
        {
            return base.Execute(requestUrl, "DELETE", post);
        }

        protected override HttpWebRequest CreateRequest(
            Uri requestUrl, string httpMethod, string post, IDictionary<string, string> headers)
        {
            if (this.RequireSecureAccess)
            {
                if (httpMethod == "GET")
                {
                    requestUrl = Auths.Sign(
                        requestUrl, httpMethod, this.ApiKey, this.ApiKeySecret, this.AccessToken, this.AccessTokenSecret);
                }
                else
                {
                    if (headers == null)
                    {
                        headers = new Dictionary<string, string>();
                    }

                    headers.Add(
                        "Authorization", 
                        Auths.GetAuthHeader(requestUrl, httpMethod, this.ApiKey, this.ApiKeySecret, this.AccessToken, this.AccessTokenSecret)
                        );
                }
            }

            var request = base.CreateRequest(requestUrl, httpMethod, post, headers);
            request.Headers.Add("X-HTTP-Method-Override", httpMethod);

            return request;
        }
    }
}
